/**
 * Filename: d:\CODE\FTP\FTP_TEST\FTP\static\js\page_2.js
 * Path: d:\CODE\FTP\FTP_TEST\FTP\static\js
 * Created Date: Wednesday, May 11th 2022, 4:18:32 pm
 * Author: xiguan
 * 
 * Copyright (c) 2022 XiGuan Inc.
 */


const basic_url = "http://127.0.0.1:8880";

let current_syncdir_id = 0; // 当前同步目录编号
let current_server_port = 21; //当前监听端口
let current_interclock_id = 0; //当前同步定时器id

// 封装ajax请求

function ajax(params){
    let url = basic_url+params.url;
    let data = params.data;
    let method = "GET";
    if(params.method !== ""){
        method = params.method;
    }

    return $.ajax({
        url : url,
        data : data,
        method: method
    });
}

// 传送同步目录编号，获取同步目录下的文件信息
async function get_syncdir_detail(id) {
    let params = {
        url: "/sync/get_sync_detail/",
        data: {
            "id": id
        }
    };
    $("#content2-client-files").html("");
    ajax(params).then(data => {
        let str =   '<table class="table">' +
                    '<thead>' +
                        '<tr>' +
                            '<th>名称</th>' +
                            '<th>类型</th>' +
                            '<th>大小</th>' +
                            '<th>修改日期</th>' +
                            '<th>创建日期</th>' +
                        '</tr>' +
                    '</thead>' +
                    '<tbody>';
        let files = JSON.parse(data);
        for(let i=0; i<files.length; i++) {
            if(i%2 === 0) {
                str += '<tr class="info">';
            } else {
                str += '<tr class="active">'
            }
            str +=          '<td>'+ files[i].name +'</td>' +
                            '<td>'+ files[i].type +'</td>' +
                            '<td>'+ files[i].size +'</td>' +
                            '<td>'+ files[i].mtime +'</td>' +
                            '<td>'+ files[i].ctime +'</td>' +
                        '</tr>';
        }
        str +=  '</tbody>' +
                '</table>';
        $("#content2-client-files").append(str);

    })
}

// 传入当前监听端口，获取服务端的目录信息
async function get_server_detail(port) {
    let params = {
        url: "/ftp/get_server_detail/",
        data: {
            "port": port
        }
    };
    ajax(params).then(async data => {
        let files = JSON.parse(data.files)
        if(data.status === "No") {
            var dialog = bootbox.dialog({
                message:    '<p class="text-center mb-0">FTP 服务器连接失败，请检查：</p>' +
                            '<p class="text-danger">1. 是否已经启动 FTP 服务器</p> ' +
                            '<p class="text-danger">2. 侦听端口是否正确配置</p>      ',
                closeButton: false
            });
            setTimeout(async function () {
                dialog.modal('hide');
            },4000);
        }
        else {
            await $("#content2-server-files").html("");
            let str =   '<table class="table">' +
                        '<thead>' +
                            '<tr>' +
                                '<th>名称</th>' +
                                '<th>大小</th>' +
                                '<th>权限</th>' +
                                '<th>修改日期</th>' +
                                '<th>操作</th>' +
                            '</tr>' +
                        '</thead>' +
                        '<tbody>';
            for(let i=0; i<files.length; i++) {
                if(i%2 === 0) {
                    str += '<tr class="info">';
                } else {
                    str += '<tr class="active">'
                }
                str +=          '<td>'+ files[i].name +'</td>' +
                                '<td>'+ files[i].size +'</td>' +
                                '<td>'+ files[i].chmod +'</td>' +
                                '<td>'+ files[i].mtime +'</td>' +
                                '<td><a href="#" onclick="content2_server_rename(`' + files[i].name +'`) " id="content2-server-rename-icon"><span class="glyphicon-asterisk"></span></a>' +
                                '<a href="#" onclick="content2_server_del(`' + files[i].name +'`) " id="content2-server-del-icon"><span class="glyphicon-minus"></span></a></td>' +
                            '</tr>';
            }
            str +=  '</tbody>' +
                    '</table>';
            $("#content2-server-files").append(str);
        }
    });
}

// 传入文件名，删除服务端的文件
function content2_server_del(name) {
    // 确认框
    bootbox.confirm({
        message: "服务端：确认删除吗?",
        buttons: {
                confirm: {
                    label: '确定',
                },
                cancel: {
                    label: '取消',
                }
        },
        callback: async function (result) {
            if (result) {
                let params = {
                    url: "/ftp/del_server_file/",
                    data: {
                        "name": name
                    }
                };
                ajax(params).then(async data => {
                    if(data === "OK") {
                        await get_server_detail(current_server_port);
                    }
                })
            }
        }
    });

}

// 传入文件名，重命名文件
function content2_server_rename(name) {

    var dialog = bootbox.dialog({
        title: '服务端：文件重命名',
        message: "重命名：<input type='text' id='content2-rename-file-name' value='" + name + "'" + " style='width: 210px;'/>",
        size: 'small',
        buttons: {
            cancel: {
                label: "取消",
            },
            ok: {
                label: "确认",
                callback: async function(){
                    let params = {
                        url: "/ftp/rename_server_file/",
                        data: {
                            "fromname": name,
                            "toname": $("#content2-rename-file-name").val()
                        }
                    };
                    await ajax(params).then(async data => {
                        if (data === "OK") {
                            var dialog = bootbox.dialog({
                                message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> 服务端正在重命名...</p>',
                                closeButton: false
                            });
                            setTimeout(async function (){
                                dialog.modal('hide');
                                await get_server_detail(current_server_port);
                            },2000);
                        } else {
                            var dialog = bootbox.dialog({
                                message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> 重命名出错，请检查名称是否合法！</p>',
                                closeButton: false
                            });
                            setTimeout(async function (){
                                dialog.modal('hide');
                            },2000);
                        }
                    })
                }
            }
        }
    })

}
// 获取同步目录
async function get_all_syncdir() {
    $(".content1-syncdir-item").remove();
    let params = {
        url: "/sync/get_all"
    };
    await ajax(params).then(data => {
        let syncdirs = JSON.parse(data);
        if(syncdirs.length !== 0) {
            current_syncdir_id = syncdirs[0].id
            current_server_port = syncdirs[0].port
        }
        for(let i=0; i<syncdirs.length; i++) {
            str =   '<div class="content1-syncdir-item">' +
                        '<text class="content1-syncdir-item-no">同步编号：' + syncdirs[i].id +
                        '</text>' +
                        '<text class="content1-syncdir-item-port">侦听端口：' + syncdirs[i].port +
                        '</text>' +
                        '<text class="content1-syncdir-item-del" onclick="del_syncdir('+ syncdirs[i].id +')">×' +
                        '</text>' +
                        '<text class="content1-syncdir-item-path">同步目录：' + syncdirs[i].path +
                        '</text>' +
                    '</div>'
            $('#content1').append(str);
        }
        $("#sync-dir-select-div").html("");
        str2 = '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">' +
                '同步目录<span class="caret"></span>' +
            '</button>' +
            '<ul class="dropdown-menu">'
        for(let i=0; i<syncdirs.length; i++) {
            str2 = str2 + '<li><a href="#" onclick="change_syncdir_port('+ syncdirs[i].id +','+ syncdirs[i].port +')">编号：' + syncdirs[i].id + ', 端口：'+ syncdirs[i].port+'</a></li>';
        }
        str2 = str2 + '</ul>';
        $('#sync-dir-select-div').append(str2);
    });
}
// 切换同步目录
async function change_syncdir_port(syncdir_id, server_port) {
    await get_syncdir_detail(syncdir_id);
    await get_server_detail(server_port);
    current_syncdir_id = syncdir_id;
    current_server_port = server_port;
}

$(async function() {

    $(".left-container-nav-select").attr("class","left-container-nav-basic")
    $(".left-container-nav-title-select").attr("class", "left-container-nav-title-basic")
    // 自动同步
    $("#auto-sync-switch").bootstrapSwitch({
        onText: "自动",
        offText: "手动",
        onColor: "primary",
        offColor: "danger",
        size: "normal",
        onSwitchChange: function (event, state) {
            if (state === true) {
                current_interval_id = setInterval(() => {
                    $("#content2-client-sync-btn").click();
                }, 60000);
            } else {
                clearInterval(current_interval_id);
            }
        }
    });

    await get_server_detail(current_server_port);
    await get_all_syncdir();

    // 点击服务端新增同步目录按钮
    $("#content2-server-mkdir-btn").click(async () => {
        var dialog = bootbox.dialog({
            title: '服务端：新建目录',
            message: "目录名：<input type='text' id='content2-add-dir-name' style='width: 210px;'/>",
            size: 'small',
            buttons: {
                cancel: {
                    label: "取消",
                },
                ok: {
                    label: "确认",
                    callback: async function(){
                        let params = {
                            url: "/ftp/add_server_dir/",
                            data: {
                                "name": $("#content2-add-dir-name").val(),
                            }
                        };
                        await ajax(params).then(async data => {
                            console.info(data);
                            if (data === "OK") {
                                var dialog = bootbox.dialog({
                                    message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> 服务端正在新增目录...</p>',
                                    closeButton: false
                                });
                                setTimeout(async function (){
                                    dialog.modal('hide');
                                    await get_server_detail(current_server_port);
                                },2000);
                            } else {
                                var dialog = bootbox.dialog({
                                    message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> 新增目录出错，请检查名称是否合法！</p>',
                                    closeButton: false
                                });
                                setTimeout(async function (){
                                    dialog.modal('hide');
                                },2000);
                            }
                        })
                    }
                }
            }
        })
    });

    // 点击服务端同步到本地按钮
    $("#content2-server-sync-btn").click(async () => {
        var dialog = bootbox.dialog({
            message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i>服务端：正在同步文件到本地，请稍等...</p>',
            closeButton: false
        });
        let params = {
            url: "/ftp/sync_2_local/",
            data: {
                "current_syncdir_id": current_syncdir_id,
                "current_server_port": current_server_port
            }
        };
        ajax(params).then(data => {
            if(data === "OK") {
                setTimeout(async function (){
                    dialog.modal('hide');
                    await get_syncdir_detail(current_syncdir_id);
                },2000);
            } else {
                setTimeout(async function (){
                    dialog.modal('hide');
                },2000);
            }
        });

    });

    // 点击客户端上传按钮
    $("#content2-client-sync-btn").click(async () => {
        var dialog = bootbox.dialog({
            message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i>客户端：正在上传文件到服务器（已自动过滤掉忽略文件），请稍等...</p>',
            closeButton: false
        });
        let params = {
            url: "/ftp/local_upload",
            data: {
                "current_syncdir_id": current_syncdir_id,
                "current_server_port": current_server_port
            }
        };
        ajax(params).then(data => {
            if(data === "OK") {
                setTimeout(async function (){
                    dialog.modal('hide');
                    await get_server_detail(current_server_port);
                },2000);
            } else {
                setTimeout(async function (){
                    dialog.modal('hide');
                },2000);
            }
        })
    });

})